import {useLocation, useNavigate, useOutletContext} from "react-router-dom"
import {useEffect, useState} from "react"
import {getOrder, payOrder} from "../../request/order"
import {message, Radio} from "antd"
import zfbPay from './zfb-pay.svg'
import wechatPay from './wechat-pay.svg'

function Pay() {
    const [setTitle] = useOutletContext()
    useEffect(() => setTitle('支付'), [setTitle])
    const navigate = useNavigate()
    const [order, setOrder] = useState({})
    const [payWay, setPayWay] = useState(null)
    const {orderId} = useLocation().state
    useEffect(() => {
        getOrder(orderId).then(setOrder).catch(({msg}) => message.error(msg))
    }, [orderId])
    function pay() {
        if (!payWay) {
            message.error('请选择支付方式')
        } else {
            payOrder(orderId, payWay)
                .then(() => {
                    message.success('支付成功')
                    navigate('/purchase/pay-result', { state: {orderId}})
                })
                .catch(({msg}) => message.error(msg))
        }
    }
    return (
        <>
            <div className="row needPay">
                <div>支付金额</div>
                <h1>￥{order.actual_price}</h1>
            </div>
            <div className="row prop pay-select" onClick={() => setPayWay('支付宝支付')}>
                <div className="icon">
                    <img src={zfbPay} alt="zfbPay"/>
                    <b>支付宝支付</b>
                </div>
                <div className="radio">
                    <Radio checked={payWay === '支付宝支付'}/>
                </div>
            </div>
            <div className="row prop pay-select" onClick={() => setPayWay('微信支付')}>
                <div className="icon">
                    <img src={wechatPay} alt="wechatPay"/>
                    <b>微信支付</b>
                </div>
                <div className="radio">
                    <Radio checked={payWay === '微信支付'}/>
                </div>
            </div>
            <div className="big-btn" onClick={pay}>确认支付</div>
        </>
    )
}

export default Pay